<template>
  <h1>{{ title }}</h1>
  <button @click="title = 'world'">change</button>

  <!-- 留言板 -->
  <div class="box">
    <input type="text" v-model="newMessage" placeholder="请输入内容" />
    <button @click="addMessage">发布</button>
    <div>
      <ul>
        <li v-for="(item, index) in messages" :key="index">
          {{ item.content }}
          <div>
            <span @click="deleteMessage(index)" class="a">删除(下标)</span>
            <span @click="deleteMessage2(item.id)" class="a">删除(ID)</span>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
const title = ref("hello");
const newMessage = ref("");
const messages = ref([]);

// 刷新预加载本地存储留言
onMounted(() => {
  loadMessages();
});

// 从本地存储加载留言
const loadMessages = () => {
  let str = localStorage.getItem("messages");
  if (str) {
    item.value = JSON.parse(str);
  }
};

// 利用watch监听mssages数组，储存到本地储存
watch(messages.value, (MessagesNew) => {
  console.log("watch", MessagesNew);
  localStorage.setItem("messages", JSON.stringify(MessagesNew));
});

// 发布内容
const addMessage = () => {
  // 给用户提示
  if (newMessage.value == "") {
    alert("你还没有输入内容!");
    return;
  }
  messages.value.unshift({ id: Date.now(), content: newMessage.value });
  newMessage.value = ""; // 清空输入框
  return;
};

// 删除内容(下标)
const deleteMessage = (index) => {
  if (confirm(`确定要删除[${messages.value[index].content}]吗?`)) {
    messages.value.splice(index, 1);
  }
  return;
};
// 删除内容(ID)
const deleteMessage2 = (id) => {
  let index = messages.value.findIndex(
    (messages) => parseInt(messages.id) === parseInt(id)
  );
  if (confirm(`确定要删除[${messages.value[index].content}]吗?`)) {
    messages.value.splice(index, 1);
  }
  return;
};
</script>

<style  scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.box {
  width: 250px;
  height: 400px;
  margin: 20px auto;
}
ul {
  list-style: none;
  padding: 0;
}
li {
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
button {
  margin-left: 20px;
}
.a {
  color: red;
  cursor: pointer;
}
</style>